package com.tarena.lbs.basic.web.controller;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.web.service.AdminService;
import com.tarena.lbs.basic.web.thread.CustomThreadLocal;
import com.tarena.lbs.common.passport.encoder.JwtEncoder;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.param.AdminParam;
import com.tarena.lbs.pojo.basic.query.AdminQuery;
import com.tarena.lbs.pojo.basic.vo.AdminVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 专门处理和admin业务相关的接口控制层
 */
@RestController
@Slf4j
public class AdminController {
    @Autowired
    private JwtEncoder<UserPrinciple> jwtEncoder;
    @Autowired
    private AdminService adminService;
    //@Autowired
    //private CustomThreadLocal<UserPrinciple> customThreadLocal;
    /**
     * 参考笔记中的 查询admin账号详情的接口文档表格内容
     */
    //凭什么 你的controller怎么接参数 加几个注解 写几个入参 springmvc就乖乖的把参数给你了
    @GetMapping("/admin/basic/role/detail")
    public Result<AdminVO> detail() throws BusinessException {
        //Thread thread = Thread.currentThread();
        //log.info("控制层执行完毕,当前线程:{}",thread);
        //UserPrinciple userPrinciple = customThreadLocal.get();
        //log.info("控制层拿到过滤器上游存储的对象:{}",userPrinciple);
        //1. 怎么从代码中拿到请求头 Authorization
        //Integer id=parseJwt2User(jwt);
        //request.getHeader("Authorization");
        //2.调用业务层 查询adminVO
        AdminVO vo=adminService.detail();
        return new Result<>(vo);
    }

    private Integer parseJwt2User(String jwt) throws BusinessException {
        if (jwt!=null&&jwt.length()>0){
            log.info("拿到jwt,非空:{},开始解析",jwt);
            UserPrinciple userPrinciple = jwtEncoder.getLoginFromToken(jwt, UserPrinciple.class);
            return userPrinciple.getId();
        }else{
            log.error("没有jwt,查不到任何数据");
            throw new BusinessException("-2","jwt没值");
        }
    }
    @PostMapping("/admin/basic/role/list")
    public Result<PageResult<AdminVO>> adminPage(@RequestBody AdminQuery query)
            throws BusinessException{
        PageResult<AdminVO> voPages=adminService.adminPage(query);
        return new Result<>(voPages);
    }
    //后台新增账号
    @PostMapping("/admin/basic/role/add")
    public Result<Void> adminSave(@RequestBody AdminParam param)
            throws BusinessException{
        adminService.adminSave(param);
        return Result.success();
    }

}







































